<?php

namespace addons\booking\model;

use think\Model;


class Calendar extends Model
{

    // 表名
    protected $name = 'booking_calendar';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'day_time_text'
    ];


    public function getDayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['day_time']) ? $data['day_time'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    protected function setDayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 日历价格的计算
     *
     * @param $house_id
     * @param $price 默认的价格
     * @param $start_time
     * @param $end_time
     * @param $orderInfo
     * @return void
     */
    public static function calculate($house_id, $price, $start_time, $end_time, &$orderInfo)
    {
        $startTime = is_numeric($start_time) ? $start_time : strtotime($start_time);
        $endTime = is_numeric($end_time) ? $end_time : strtotime($end_time);
        $data = self::where('house_id', $house_id)->where('day_time', 'between', [$startTime, $endTime])->select();
        $newData = [];
        foreach ($data as $item) {
            $newData[$item['day_time']] = $item['price'];
        }
        $time = 24 * 60 * 60;
        $calendar_price = [];
        //第一天为开始计算价格，最后一天已离去，不计算
        for ($i = $startTime; $i < $endTime; $i += $time) {
            if (isset($newData[$i])) {
                $orderInfo['amount'] = bcadd($orderInfo['amount'], $newData[$i], 2);
                $calendar_price[$i] = $newData[$i];
            } else {
                $orderInfo['amount'] = bcadd($orderInfo['amount'], $price, 2);
                $calendar_price[$i] = $price;
            }
        }
        $orderInfo['params']['calender_price'] = $calendar_price;
    }
}
